package com.shuma.upms.user.controller;

import com.shuma.upms.user.domain.dto.PasswordResetDTO;
import com.shuma.upms.user.domain.dto.UserLoginDTO;
import com.shuma.upms.user.domain.dto.UserRegisterDTO;
import com.shuma.upms.user.domain.dto.UserUpdateDTO;
import com.shuma.upms.user.domain.entity.Result;
import com.shuma.upms.user.domain.vo.LoginSuccessVO;
import com.shuma.upms.user.domain.vo.PageVO;
import com.shuma.upms.user.domain.vo.UserInfoVo;
import com.shuma.upms.user.exception.BusinessException;
import com.shuma.upms.user.service.PermissionCheckService;
import com.shuma.upms.user.service.UserService;
import com.shuma.upms.user.service.impl.PermissionCheckServiceImpl;
import com.shuma.upms.user.util.UserContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;
import java.util.Objects;

@Slf4j
@RestController
@RequestMapping("/users")
@Validated
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private PermissionCheckService permissionCheckService;

    /**
     * 用户登录
     * @param loginDTO 登录信息
     * @param request  请求对象
     * @return 包含token的登录成功信息
     */
    @PostMapping("/login")
    public Result<LoginSuccessVO> login(@RequestBody @Valid UserLoginDTO loginDTO, HttpServletRequest request) {
        String ip = getClientIpAddress(request);
        log.info("收到用户 [{}] 的登录请求", loginDTO.getUsername());
        LoginSuccessVO loginData = userService.login(loginDTO,ip);
        return Result.success(loginData);
    }


    /**
     * 用户注册
     * @param registerDTO 注册信息
     * @param request     请求对象
     * @return 操作结果
     */
    @PostMapping("/register")
    public Result<Void> register(@RequestBody @Valid UserRegisterDTO registerDTO, HttpServletRequest request) {
        String ipAddress = getClientIpAddress(request);
        log.info("收到用户 [{}] 的注册请求，IP地址: {}", registerDTO.getUsername(), ipAddress);
        userService.register(registerDTO, ipAddress);
        return Result.success();
    }

    /**
     * 分页查询用户列表
     * @return 用户信息列表
     */
    @GetMapping
    public Result<PageVO<UserInfoVo>> listUsers(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize) {
        PageVO<UserInfoVo> pageResult = userService.listUsers(pageNum, pageSize);
        return Result.success(pageResult);
    }

    /**
     * 根据ID查询用户信息
     * @param userId 用户ID
     * @return 用户详细信息
     */
    @GetMapping("/{userId}")
    public Result<UserInfoVo> getUserInfo(@PathVariable Long userId) {
        // 权限检查：读取目标用户信息
        permissionCheckService.checkReadPermission(userId);
        UserInfoVo userInfo = userService.getUserInfo(userId);
        return Result.success(userInfo);
    }

    /**
     * 根据ID修改用户信息
     * @param userId 用户ID
     * @param dto    更新信息
     * @param request 请求对象
     * @return 操作结果
     */
    @PutMapping("/{userId}")
    public Result<Void> updateUserInfo(@PathVariable Long userId, @RequestBody @Valid UserUpdateDTO dto, HttpServletRequest request) {
        String ip = getClientIpAddress(request);
        // 权限检查：修改目标用户信息
        permissionCheckService.checkWritePermission(userId);
        userService.updateUserInfo(userId, dto, ip);
        return Result.success();
    }

    /**
     * 重置用户密码
     * @param userId 用户ID
     * @param dto    新密码信息
     * @param request 请求对象
     * @return 操作结果
     */
    @PostMapping("/{userId}/reset-password")
    public Result<Void> resetPassword(@PathVariable Long userId, @RequestBody @Valid PasswordResetDTO dto, HttpServletRequest request) {
        String ip = getClientIpAddress(request);
        // 权限检查：重置目标用户密码
        permissionCheckService.checkWritePermission(userId);
        userService.resetPassword(userId, dto, ip);
        return Result.success();
    }


    /**
     * 获取客户端真实IP地址
     * @param request 请求对象
     * @return 客户端IP地址
     */
    private String getClientIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        // 对于多级代理，第一个IP为客户端真实IP
        if (ip != null && ip.contains(",")) {
            ip = ip.split(",")[0];
        }
        return ip;
    }

}